﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Xml.Linq;
using CPlatePrintSys.Annotation.Converters;
using CPlatePrintSys.Annotation.Events;
using CPlatePrintSys.Annotation.Models;
using CPlatePrintSys.Domain.Events;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Infrastructure;
using netDxf;
using netDxf.Entities;
using netDxf.Tables;
using Prism.Events;
using Prism.Navigation.Regions;
using Newtonsoft.Json;
using System.Threading;
using netDxf.Header;

namespace CPlatePrintSys.Annotation
{
    /// <summary>
    /// 负责标注信息的添加、删除、修改、以及最终文件保存等操作协调管理。
    /// </summary>
    public class AnnotationManager
    {
        public readonly double DefaultSheetWidth = 1000.0;      // 默认图纸宽度
        public readonly double DefaultSheetHeight = 1000.0;     // 默认图纸高度
        public readonly string DefaultSpecLayerName = "spec";   // 默认规格图层名称

        private IEventAggregator _eventAggregator;
        private IRegionManager _regionManager;

        private static AnnotationManager _instance;
        private static readonly object _lock = new object();

        public static AnnotationManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new AnnotationManager();
                        }
                    }
                }
                return _instance;
            }
        }


        /// <summary>
        /// 存储所有的标注图层信息(包括颜色等）。
        /// </summary>
        private List<Layer> _layers = new List<Layer>();

        /// <summary>
        /// 存储所有的标注信息，按图层分组。
        /// </summary>
        private Dictionary<string, List<EntityObject>> _layeredAnnotations = new Dictionary<string, List<EntityObject>>();

        /// <summary>
        /// 所有零件的DXF文档列表。
        /// </summary>
        private List<DxfDocument> _parts = new List<DxfDocument>();

        /// <summary>
        /// 当前编辑的DXF文档（用户修改后的版本）
        /// </summary>
        private Dictionary<string, DxfDocument> _currentEditingDocuments = new Dictionary<string, DxfDocument>();


        public PlateAnnotationInfo CurrentEditAnnotationInfo { get; private set; }

        /// <summary>
        /// 注册编辑文档
        /// </summary>
        public void RegisterEditingDocument(string controlId, DxfDocument document)
        {
            _currentEditingDocuments[controlId] = document;
            System.Diagnostics.Debug.WriteLine($"注册编辑文档: {controlId} -> {document?.Name ?? "null"}");
        }
        
        /// <summary>
        /// 获取编辑文档
        /// </summary>
        public DxfDocument GetEditingDocument(string controlId)
        {
            return _currentEditingDocuments.ContainsKey(controlId) ? _currentEditingDocuments[controlId] : null;
        }

        /// <summary>
        /// 清理所有缓存和映射数据，确保切换图纸时状态完全重置
        /// </summary>
        private void ClearAllCachesAndMappings()
        {
            System.Diagnostics.Debug.WriteLine("=== 开始清理所有缓存和映射数据 ===");
            
            // 清理零件文档列表
            _parts.Clear();
            System.Diagnostics.Debug.WriteLine("已清理 _parts 列表");
            
            // 清理当前编辑文档映射
            _currentEditingDocuments.Clear();
            System.Diagnostics.Debug.WriteLine("已清理 _currentEditingDocuments 映射");
            
            // 清理按图层分组的标注信息
            _layeredAnnotations.Clear();
            System.Diagnostics.Debug.WriteLine("已清理 _layeredAnnotations 映射");
            
            // 清理图层列表
            _layers.Clear();
            System.Diagnostics.Debug.WriteLine("已清理 _layers 列表");
            
            // 清理当前编辑的标注信息
            this.CurrentEditAnnotationInfo = null;
            System.Diagnostics.Debug.WriteLine("已清理 CurrentEditAnnotationInfo");
            
            // 发布清理事件，通知所有控件清理其内部状态
            this._eventAggregator.GetEvent<ClearAnnotationCacheEvent>().Publish(new ClearAnnotationCacheEventArgs());
            System.Diagnostics.Debug.WriteLine("已发布清理事件通知所有控件");
            
            System.Diagnostics.Debug.WriteLine("=== 缓存和映射数据清理完成 ===");
        }

        private AnnotationManager()
        {

        }


        public void Initialize()
        {
            this._regionManager = (IRegionManager)Prism.Ioc.ContainerLocator.Container.Resolve(typeof(IRegionManager));

            // 私有构造函数，防止外部实例化
            this._eventAggregator = (IEventAggregator)Prism.Ioc.ContainerLocator.Container.Resolve(typeof(IEventAggregator));
            this._eventAggregator.GetEvent<EditPlateAnnotationEvent>().Subscribe(OnEditPlateAnnotation);
            this._eventAggregator.GetEvent<SaveAnnotationEvent>().Subscribe(OnSaveAnnotion);


            // 初始化相机同步管理器
            CameraSyncExtensions.InitializeCameraSync(this._eventAggregator);
        }


        private async void OnEditPlateAnnotation(PlateAnnotationInfo info)
        {
            ClearAllCachesAndMappings();
            this.CurrentEditAnnotationInfo = info;

            var tmpDataPath = EnsureTempDirectoryExists();

            // 根据布局模式处理不同的逻辑
            switch (info.LayoutMean)
            {
                case LayoutMean.MirrorLayout:
                    await HandleMirrorLayout(info, tmpDataPath);
                    break;
                case LayoutMean.MergedLayout:
                    await HandleMergedLayout(info, tmpDataPath);
                    break;
                default: // Unprocessed
                    await HandleUnprocessedLayout(info, tmpDataPath);
                    break;
            }
        }

        /// <summary>
        /// 确保临时目录存在
        /// </summary>
        /// <returns>临时目录路径</returns>
        private string EnsureTempDirectoryExists()
        {
            string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string tmpDataPath = Path.Combine(appDirectory, "temp");
            if (!Directory.Exists(tmpDataPath))
            {
                Directory.CreateDirectory(tmpDataPath);
            }
            return tmpDataPath;
        }

        /// <summary>
        /// 导航到DxfAnnotationView并发布布局模式事件
        /// </summary>
        /// <param name="layoutMode">布局模式</param>
        private void NavigateAndPublishLayoutMode(LayoutMode layoutMode)
        {
            _regionManager.RequestNavigate(ConstStrings.UI_Region_Main_Content, "DxfAnnotationView");
            this._eventAggregator.GetEvent<LayoutModeChangedEvent>().Publish(layoutMode);
        }

        /// <summary>
        /// 加载DXF文档（支持DXF和SDB格式）
        /// </summary>
        /// <param name="info">标注信息</param>
        /// <param name="tmpDataPath">临时目录路径</param>
        /// <returns>加载的DXF文档</returns>
        private DxfDocument LoadDxfDocument(PlateAnnotationInfo info, string tmpDataPath)
        {
            // 首先检查是否已存在临时DXF文件
            var existingDxfFilePath = Path.Combine(tmpDataPath, $"{info.SheetConsistentNo}.dxf");
            if (File.Exists(existingDxfFilePath))
            {
                var dxfDoc = DxfDocument.Load(existingDxfFilePath);
                var verString = DxfDocument.CheckDxfFileVersion(existingDxfFilePath);
                if (dxfDoc != null)
                {
                    System.Diagnostics.Debug.WriteLine($"已加载现有DXF文件: {existingDxfFilePath}");
                    return dxfDoc;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"加载失败，现有DXF文件的版本: {verString}");
                }
            }

            // 从原始设计图路径加载
            var fileExtension = Path.GetExtension(info.DesignDrawingPath).ToLower();
            if (fileExtension.Contains("dxf") && File.Exists(info.DesignDrawingPath))
            {
                return DxfDocument.Load(info.DesignDrawingPath);
            }
            else if (fileExtension.Contains("sdb"))
            {
                return LoadSdbAndConvertToDxf(info, tmpDataPath);
            }

            return null;
        }

        /// <summary>
        /// 加载SDB文件并转换为DXF
        /// </summary>
        /// <param name="info">标注信息</param>
        /// <param name="tmpDataPath">临时目录路径</param>
        /// <returns>转换后的DXF文档</returns>
        private DxfDocument LoadSdbAndConvertToDxf(PlateAnnotationInfo info, string tmpDataPath)
        {
            string tmpfilePath = Path.Combine(tmpDataPath, info.SheetConsistentNo + ".dxf");

            Task.Factory.StartNew(() =>
            {
                DxfConverterWrapper.ConvertSDB2Dxf(info.DesignDrawingPath, tmpfilePath);
            }).Wait(); // 等待转换完成

            if (File.Exists(tmpfilePath))
            {
                return DxfDocument.Load(tmpfilePath);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"转换后的DXF文件不存在: {tmpfilePath}");
                return null;
            }
        }

        /// <summary>
        /// 处理镜像布局
        /// </summary>
        /// <param name="info">标注信息</param>
        /// <param name="tmpDataPath">临时目录路径</param>
        private async Task HandleMirrorLayout(PlateAnnotationInfo info, string tmpDataPath)
        {
            NavigateAndPublishLayoutMode(LayoutMode.MirrorLayout);

            var dxfDoc = LoadDxfDocument(info, tmpDataPath);
            if (dxfDoc == null) return;

            dxfDoc.Name = info.SheetConsistentNo;
            _parts.Add(dxfDoc);

            // 创建镜像文档和映射关系
            var mirrorResult = DxfMirrorConverter.MirrorWithMapping(dxfDoc, MirrorDirection.Vertical);
            if (mirrorResult?.MirroredDocument != null)
            {
                mirrorResult.MirroredDocument.Name = $"{dxfDoc.Name}_Mirrored";
                _parts.Add(mirrorResult.MirroredDocument);

                MirrorEntityMappingManager.RegisterMirrorResult(mirrorResult.MirroredDocument.Name, mirrorResult);

                System.Diagnostics.Debug.WriteLine($"镜像文档创建成功: {mirrorResult.MirroredDocument.Name}");
                System.Diagnostics.Debug.WriteLine($"映射关系已注册，包含 {mirrorResult.HandleMapping.Count} 个实体映射");
            }

            await Task.Delay(50);

            // 发布显示事件
            this._eventAggregator.GetEvent<DisplayDxfPart>().Publish(new DisplayDxfPartArgs { ControlId = "normal", Document = dxfDoc });
            this._eventAggregator.GetEvent<DisplayDxfPart>().Publish(new DisplayDxfPartArgs { ControlId = "mirror", Document = mirrorResult.MirroredDocument });
        }

        /// <summary>
        /// 处理合并布局
        /// </summary>
        /// <param name="info">标注信息</param>
        /// <param name="tmpDataPath">临时目录路径</param>
        private async Task HandleMergedLayout(PlateAnnotationInfo info, string tmpDataPath)
        {
            NavigateAndPublishLayoutMode(LayoutMode.MergedLayout);

            // 解析LayoutInfo
            var layoutInfo = ParseLayoutInfo(info);
            if (layoutInfo == null) return;

            var mergedName = Path.Combine(tmpDataPath, $"{info.SheetConsistentNo}.dxf");
            if (File.Exists(mergedName))
            {
                await HandleExistingMergedDocument(mergedName);
            }
            else
            {
                await CreateNewMergedDocument(info, layoutInfo);
            }
        }

        /// <summary>
        /// 处理未处理布局（普通布局）
        /// </summary>
        /// <param name="info">标注信息</param>
        /// <param name="tmpDataPath">临时目录路径</param>
        private async Task HandleUnprocessedLayout(PlateAnnotationInfo info, string tmpDataPath)
        {
            NavigateAndPublishLayoutMode(LayoutMode.MergedLayout);

            var dxfDoc = LoadDxfDocument(info, tmpDataPath);
            if (dxfDoc == null) return;

            dxfDoc.Name = info.SheetConsistentNo;
            _parts.Add(dxfDoc);

            await Task.Delay(50);

            this._eventAggregator.GetEvent<DisplayDxfPart>().Publish(new DisplayDxfPartArgs { ControlId = "normal", Document = dxfDoc });
        }

        /// <summary>
        /// 解析布局信息
        /// </summary>
        /// <param name="info">标注信息</param>
        /// <returns>解析后的布局信息</returns>
        private LayoutInfo ParseLayoutInfo(PlateAnnotationInfo info)
        {
            if (string.IsNullOrEmpty(info.LayoutInfo))
            {
                System.Diagnostics.Debug.WriteLine("LayoutInfo为空，无法处理合并布局");
                return null;
            }

            var layoutInfo = JsonConvert.DeserializeObject<LayoutInfo>(info.LayoutInfo);
            if (layoutInfo?.Merged?.PartLayouts == null || !layoutInfo.Merged.PartLayouts.Any())
            {
                System.Diagnostics.Debug.WriteLine("LayoutInfo解析失败或没有零件布局信息");
                return null;
            }

            return layoutInfo;
        }

        /// <summary>
        /// 处理已存在的合并文档
        /// </summary>
        /// <param name="mergedFilePath">合并文档路径</param>
        private async Task HandleExistingMergedDocument(string mergedFilePath)
        {
            var mergedDocument = DxfDocument.Load(mergedFilePath);
            System.Diagnostics.Debug.WriteLine($"已加载现有DXF文件: {mergedFilePath}");

            _parts.Add(mergedDocument);

            await Task.Delay(50);

            this._eventAggregator.GetEvent<DisplayDxfPart>().Publish(
                new DisplayDxfPartArgs { ControlId = "normal", Document = mergedDocument });
        }

        /// <summary>
        /// 创建新的合并文档
        /// </summary>
        /// <param name="info">标注信息</param>
        /// <param name="layoutInfo">布局信息</param>
        private async Task CreateNewMergedDocument(PlateAnnotationInfo info, LayoutInfo layoutInfo)
        {
            var mergedDocument = new DxfDocument(DxfVersion.AutoCad2013);
            mergedDocument.Name = info.SheetConsistentNo;

            // 设置图纸尺寸
            double sheetWidth = layoutInfo.Merged.SheetWidth / 10;
            double sheetLength = layoutInfo.Merged.SheetLongth / 10;

            System.Diagnostics.Debug.WriteLine($"=== 合并布局处理开始 ===");
            System.Diagnostics.Debug.WriteLine($"图纸尺寸: 宽度={sheetWidth}, 长度={sheetLength}");
            System.Diagnostics.Debug.WriteLine($"零件数量: {layoutInfo.Merged.PartLayouts.Count}");

            // 添加图纸边界线
            var boundaryEntities = CreateSheetBoundary(sheetWidth, sheetLength);
            foreach (var entity in boundaryEntities)
            {
                mergedDocument.Entities.Add(entity);
            }
            System.Diagnostics.Debug.WriteLine($"图纸边界线添加完成，边界实体数量: {boundaryEntities.Count}");

            await Task.Factory.StartNew(() =>
            {
                // 异步处理每个零件的布局
                foreach (var partLayout in layoutInfo.Merged.PartLayouts)
                {
                    System.Diagnostics.Debug.WriteLine($"处理零件布局: {partLayout.SheetConsistentNo}, 位置({partLayout.Position.X:F2},{partLayout.Position.Y:F2}), 旋转={partLayout.Rotation:F2}°");
                    ProcessPartLayout(partLayout, mergedDocument, info);
                }
            }).ContinueWith(sync =>
            {
                // 处理完成后，检查合并后的文档状态
                System.Diagnostics.Debug.WriteLine($"合并文档状态检查:");
                System.Diagnostics.Debug.WriteLine($"  文档名称: {mergedDocument.Name}");
                System.Diagnostics.Debug.WriteLine($"  实体总数: {mergedDocument.Entities.All.Count()}");
                System.Diagnostics.Debug.WriteLine($"  图层数量: {mergedDocument.Layers.Count}");
                
                _parts.Add(mergedDocument);

                this._eventAggregator.GetEvent<DisplayDxfPart>().Publish(
                    new DisplayDxfPartArgs { ControlId = "normal", Document = mergedDocument });
                System.Diagnostics.Debug.WriteLine($"合并布局处理完成，文档名称: {mergedDocument.Name}");
                System.Diagnostics.Debug.WriteLine($"=== 合并布局处理结束 ===");
            });
        }

        /// <summary>
        /// 创建图纸边界线
        /// </summary>
        /// <param name="width">宽度</param>
        /// <param name="length">长度</param>
        /// <returns>边界线实体列表</returns>
        private List<EntityObject> CreateSheetBoundary(double width, double length)
        {
            var entities = new List<EntityObject>();

            // 创建矩形边界 - 使用正确的 netDxf API
            // 注意：这里 width 对应 Y 坐标，length 对应 X 坐标
            var rectangle = new Polyline2D();
            rectangle.Vertexes.Add(new Polyline2DVertex(0, 0));
            rectangle.Vertexes.Add(new Polyline2DVertex(length, 0));
            rectangle.Vertexes.Add(new Polyline2DVertex(length, width));
            rectangle.Vertexes.Add(new Polyline2DVertex(0, width));
            rectangle.IsClosed = true;

            // 设置边界线的属性
            rectangle.Color = AciColor.Cyan;
            rectangle.Layer = new Layer("BOUNDARY");
            rectangle.Linetype = Linetype.Continuous;
            rectangle.Lineweight = Lineweight.Default;

            entities.Add(rectangle);

            // 添加调试信息
            System.Diagnostics.Debug.WriteLine($"创建图纸边界: 宽度={width}, 长度={length}");
            System.Diagnostics.Debug.WriteLine($"边界顶点: (0,0), ({length},0), ({length},{width}), (0,{width})");

            return entities;
        }

        /// <summary>
        /// 处理单个零件的布局
        /// </summary>
        /// <param name="partLayout">零件布局信息</param>
        /// <param name="mergedDocument">合并后的文档</param>
        /// <param name="info">标注信息</param>
        private  void ProcessPartLayout(PartLayout partLayout, DxfDocument mergedDocument, PlateAnnotationInfo info)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"=== 开始处理零件布局: {partLayout.SheetConsistentNo} ===");

                // 异步加载零件DXF文件
                DxfDocument partDocument = LoadPartDocumentAsync(partLayout.FilePath).GetAwaiter().GetResult();
                if (partDocument == null)
                {
                    System.Diagnostics.Debug.WriteLine($"无法加载零件文档: {partLayout.FilePath}");
                    return;
                }

                System.Diagnostics.Debug.WriteLine($"零件文档加载成功: {partDocument.Name}, 实体数量: {partDocument.Entities.All.Count()}");

                // 计算变换矩阵
                var transformMatrix = CalculateTransformMatrix(partLayout);
                System.Diagnostics.Debug.WriteLine($"变换矩阵计算完成: M31={transformMatrix.M31:F2}, M32={transformMatrix.M32:F2}");

                // 记录变换前的实体数量
                int beforeCount = mergedDocument.Entities.All.Count();

                // 复制并变换零件实体到合并文档
                CopyAndTransformEntities(partDocument, mergedDocument, transformMatrix);

                // 记录变换后的实体数量
                int afterCount = mergedDocument.Entities.All.Count();
                int addedCount = afterCount - beforeCount;

                System.Diagnostics.Debug.WriteLine($"零件 {partLayout.SheetConsistentNo} 处理完成，添加了 {addedCount} 个实体");
                System.Diagnostics.Debug.WriteLine($"=== 零件布局处理结束: {partLayout.SheetConsistentNo} ===");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"处理零件布局时发生错误: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// 加载零件文档
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>DXF文档</returns>
        private async Task<DxfDocument> LoadPartDocumentAsync(string filePath)
        {
            try
            {
                if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
                    return null;

                var fileExtension = Path.GetExtension(filePath).ToLower();
                string dxfFilePath = filePath;

                // 如果是SDB文件，先转换为DXF
                if (fileExtension.Contains("sdb"))
                {
                    string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    string tmpDataPath = Path.Combine(appDirectory, "temp");

                    if (!Directory.Exists(tmpDataPath))
                    {
                        Directory.CreateDirectory(tmpDataPath);
                    }

                    string tmpFilePath = Path.Combine(tmpDataPath,
                        Path.GetFileNameWithoutExtension(filePath) + ".dxf");

                    // 异步等待SDB转换完成
                    DxfConverterWrapper.ConvertSDB2Dxf(filePath, tmpFilePath);


                    dxfFilePath = tmpFilePath;
                }

                // 加载DXF文档
                if (File.Exists(dxfFilePath))
                {
                    return DxfDocument.Load(dxfFilePath);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"DXF文件不存在: {dxfFilePath}");
                    return null;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载零件文档失败: {ex.Message}");
                return null;
            }
        }

        // 保存标注文件到本地tmp文件夹下，名称按照如下规则：
        //1） 如果this.CurrentEditAnnotationInfo.LayoutMean是镜像，保存2个文件
        //      normal -> this.CurrentEditAnnotationInfo.SheetConsistentNo.dxf
        //      mirror -> this.CurrentEditAnnotationInfo.SheetConsistentNo_mirror.dxf
        //2)  如果this.CurrentEditAnnotationInfo.LayoutMean是Merged
        //      normal -> LayoutInfo进行json解析，以每个part对应的SheetConsistentNo.dxf命名，实质上几个内容一样名字不同的文件
        //3)  如果this.CurrentEditAnnotationInfo.LayoutMean是Unprocessed（普通布局）
        //      normal -> this.CurrentEditAnnotationInfo.SheetConsistentNo.dxf
        private void OnSaveAnnotion(string docName)
        {
            try
            {
                if (this.CurrentEditAnnotationInfo == null)
                {
                    System.Diagnostics.Debug.WriteLine("当前没有编辑的标注信息，无法保存");
                    return;
                }
                string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
                string tmpDataPath = Path.Combine(appDirectory, "temp");
                if (!Directory.Exists(tmpDataPath))
                {
                    Directory.CreateDirectory(tmpDataPath);
                }
                // 根据布局模式决定文件名
                string fileName = this.CurrentEditAnnotationInfo.SheetConsistentNo;
                            if (this.CurrentEditAnnotationInfo.LayoutMean == LayoutMean.MirrorLayout)
            {
                // 关键修复：保存前重建镜像关系，确保数据一致性
                RebuildMirrorRelationshipBeforeSave();
                
                // 保存编辑后的文档，而不是原始文档
                foreach (var kvp in _currentEditingDocuments)
                {
                    string controlId = kvp.Key;
                    DxfDocument editingDoc = kvp.Value;
                    
                    if (editingDoc != null)
                    {
                        string mfileName = $"{editingDoc.Name}.dxf";
                        string mFilePath = Path.Combine(tmpDataPath, mfileName);
                        editingDoc.Save(mFilePath);
                        System.Diagnostics.Debug.WriteLine($"已保存标注文档: {mFilePath}");
                    }
                }
            }
                            else if (this.CurrentEditAnnotationInfo.LayoutMean == LayoutMean.MergedLayout)
            {
                // 对于合并布局，保存编辑后的文档
                var editingDoc = _currentEditingDocuments.Values.FirstOrDefault();
                if (editingDoc != null)
                {
                    foreach (var partLayout in JsonConvert.DeserializeObject<LayoutInfo>(this.CurrentEditAnnotationInfo.LayoutInfo).Merged.PartLayouts)
                    {
                        string partFileName = $"{partLayout.SheetConsistentNo}.dxf";
                        string partFilePath = Path.Combine(tmpDataPath, partFileName);
                        editingDoc.Save(partFilePath);
                        System.Diagnostics.Debug.WriteLine($"已保存零件文档: {partFilePath}");
                    }
                }
            }
            else
            {
                // 对于普通布局（Unprocessed），保存编辑后的文档
                var editingDoc = _currentEditingDocuments.Values.FirstOrDefault();
                if (editingDoc != null)
                {
                    string normalFileName = $"{fileName}.dxf";
                    string normalFilePath = Path.Combine(tmpDataPath, normalFileName);
                    editingDoc.Save(normalFilePath);
                    System.Diagnostics.Debug.WriteLine($"已保存普通布局标注文档: {normalFilePath}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("警告：没有找到编辑中的文档，无法保存普通布局标注");
                }
            }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存标注失败: {ex.Message}");
            }


        }

        /// <summary>
        /// 保存前重建镜像关系，确保数据一致性
        /// </summary>
        private void RebuildMirrorRelationshipBeforeSave()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("=== 开始重建镜像关系 ===");
                
                // 获取原始文档和镜像文档
                DxfDocument originalDoc = null;
                DxfDocument mirrorDoc = null;
                
                if (_currentEditingDocuments.ContainsKey("normal"))
                    originalDoc = _currentEditingDocuments["normal"];
                if (_currentEditingDocuments.ContainsKey("mirror"))
                    mirrorDoc = _currentEditingDocuments["mirror"];
                    
                if (originalDoc == null || mirrorDoc == null)
                {
                    System.Diagnostics.Debug.WriteLine("无法找到原始文档或镜像文档，跳过镜像关系重建");
                    System.Diagnostics.Debug.WriteLine($"原始文档: {(originalDoc != null ? "存在" : "不存在")}");
                    System.Diagnostics.Debug.WriteLine($"镜像文档: {(mirrorDoc != null ? "存在" : "不存在")}");
                    return;
                }
                
                System.Diagnostics.Debug.WriteLine($"原始文档: {originalDoc.Name}, 实体数量: {originalDoc.Entities.All.Count()}");
                System.Diagnostics.Debug.WriteLine($"镜像文档: {mirrorDoc.Name}, 实体数量: {mirrorDoc.Entities.All.Count()}");
                
                // 重新创建镜像文档，确保与原始文档的镜像关系正确
                var mirrorResult = DxfMirrorConverter.MirrorWithMapping(originalDoc, MirrorDirection.Vertical, false);
                if (mirrorResult?.MirroredDocument != null)
                {
                    System.Diagnostics.Debug.WriteLine($"镜像转换完成，新镜像文档实体数量: {mirrorResult.MirroredDocument.Entities.All.Count()}");
                    
                    // 更新镜像文档名称，保持原有名称
                    mirrorResult.MirroredDocument.Name = mirrorDoc.Name;
                    
                    // 清除原有内容并复制新的镜像内容
                    mirrorDoc.Entities.All.Cast<EntityObject>().ToList().ForEach(e => mirrorDoc.Entities.Remove(e));
                    foreach (var entity in mirrorResult.MirroredDocument.Entities.All)
                    {
                        var clonedEntity = (EntityObject)entity.Clone();
                        mirrorDoc.Entities.Add(clonedEntity);
                    }
                    
                    // 复制图层信息
                    mirrorDoc.Layers.Clear();
                    foreach (var layer in mirrorResult.MirroredDocument.Layers)
                    {
                        mirrorDoc.Layers.Add((Layer)layer.Clone());
                    }
                    
                    // 更新当前编辑文档
                    _currentEditingDocuments["mirror"] = mirrorDoc;
                    
                    // 重新注册映射关系
                    MirrorEntityMappingManager.RegisterMirrorResult(mirrorDoc.Name, mirrorResult);
                    
                    System.Diagnostics.Debug.WriteLine($"镜像关系重建完成，实体数量: {mirrorDoc.Entities.All.Count()}");
                    System.Diagnostics.Debug.WriteLine($"映射关系数量: {mirrorResult.HandleMapping.Count}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("镜像转换失败，无法重建镜像关系");
                }
                
                System.Diagnostics.Debug.WriteLine("=== 镜像关系重建完成 ===");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"重建镜像关系失败: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// 计算变换矩阵
        /// </summary>
        /// <param name="partLayout">零件布局信息</param>
        /// <param name="partInfo">零件信息</param>
        /// <returns>变换矩阵</returns>
        private Matrix3 CalculateTransformMatrix(PartLayout partLayout)
        {
            var matrix = Matrix3.Identity;

            // 先应用旋转变换，再应用位置变换
            if (partLayout.Rotation != 0)
            {
                double rotationRadians = partLayout.Rotation * Math.PI / 180.0;
                double cos = Math.Cos(rotationRadians);
                double sin = Math.Sin(rotationRadians);

                var rotationMatrix = new Matrix3(
                    cos, -sin, 0,
                    sin, cos, 0,
                    0, 0, 1
                );
                matrix *= rotationMatrix;
            }

            // 再应用位置变换
            var translationMatrix = new Matrix3(
                1, 0, 0,
                0, 1, 0,
                partLayout.Position.X/10, partLayout.Position.Y/10, 1
            );
            matrix *= translationMatrix;

            return matrix;
        }

        /// <summary>
        /// 复制并变换实体
        /// </summary>
        /// <param name="sourceDocument">源文档</param>
        /// <param name="targetDocument">目标文档</param>
        /// <param name="transformMatrix">变换矩阵</param>
        private void CopyAndTransformEntities(DxfDocument sourceDocument, DxfDocument targetDocument, Matrix3 transformMatrix)
        {
            foreach (var entity in sourceDocument.Entities.All)
            {
                try
                {
                    // 克隆实体
                    var clonedEntity = CloneEntity(entity);
                    if (clonedEntity != null)
                    {
                        // 应用变换
                        ApplyTransform(clonedEntity, transformMatrix);

                        // 添加到目标文档
                        targetDocument.Entities.Add(clonedEntity);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"复制实体失败: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 克隆实体
        /// </summary>
        /// <param name="entity">源实体</param>
        /// <returns>克隆的实体</returns>
        private EntityObject CloneEntity(EntityObject entity)
        {
            try
            {
                // 根据实体类型创建新的克隆实体
                EntityObject clonedEntity = null;

                if (entity is Line line)
                {
                    clonedEntity = new Line(line.StartPoint, line.EndPoint)
                    {
                        Color = line.Color,
                        Layer = line.Layer,
                        Linetype = line.Linetype,
                        Lineweight = line.Lineweight
                    };
                }
                else if (entity is Polyline2D polyline)
                {
                    clonedEntity = new Polyline2D(polyline.Vertexes.Select(v => new Polyline2DVertex(v.Position.X, v.Position.Y)).ToList(), polyline.IsClosed)
                    {
                        Color = polyline.Color,
                        Layer = polyline.Layer,
                        Linetype = polyline.Linetype,
                        Lineweight = polyline.Lineweight
                    };
                }
                else if (entity is Circle circle)
                {
                    clonedEntity = new Circle(circle.Center, circle.Radius)
                    {
                        Color = circle.Color,
                        Layer = circle.Layer,
                        Linetype = circle.Linetype,
                        Lineweight = circle.Lineweight
                    };
                }
                else if (entity is Arc arc)
                {
                    clonedEntity = new Arc(arc.Center, arc.Radius, arc.StartAngle, arc.EndAngle)
                    {
                        Color = arc.Color,
                        Layer = arc.Layer,
                        Linetype = arc.Linetype,
                        Lineweight = arc.Lineweight
                    };
                }
                else if (entity is Text text)
                {
                    // Text 构造函数需要 Vector3 位置，保持原有的 Vector3 类型
                    clonedEntity = new Text(text.Value, text.Position, text.Height)
                    {
                        Color = text.Color,
                        Layer = text.Layer,
                        Linetype = text.Linetype,
                        Lineweight = text.Lineweight,
                        Style = text.Style,
                        Width = text.Width,
                        Height = text.Height,
                        Rotation = text.Rotation
                    };
                }
                else if (entity is MText mtext)
                {
                    // MText 构造函数需要 Vector3 位置，保持原有的 Vector3 类型
                    clonedEntity = new MText(mtext.Position, mtext.Height)
                    {
                        Value = mtext.Value,
                        Color = mtext.Color,
                        Layer = mtext.Layer,
                        Linetype = mtext.Linetype,
                        Lineweight = mtext.Lineweight,
                        Style = mtext.Style,
                        Height = mtext.Height,
                        Rotation = mtext.Rotation
                    };
                }
                else if (entity is Dimension dimension)
                {
                    // 对于标注实体，创建基本的克隆
                    clonedEntity = dimension.Clone() as EntityObject;
                }
                else if (entity is Insert insert)
                {
                    // 对于Insert实体（块引用），创建基本的克隆
                    clonedEntity = insert.Clone() as EntityObject;
                }
                else if (entity is Point point)
                {
                    // 对于Point实体，创建新的点
                    clonedEntity = new Point(point.Position)
                    {
                        Color = point.Color,
                        Layer = point.Layer,
                        Linetype = point.Linetype,
                        Lineweight = point.Lineweight
                    };
                }
                else if (entity is MLine mline)
                {
                    // 对于MLine实体（多线），创建基本的克隆
                    clonedEntity = mline.Clone() as EntityObject;
                }
                else if (entity is Ellipse ellipse)
                {
                    // 对于Ellipse实体（椭圆），创建新的椭圆
                    clonedEntity = new Ellipse(ellipse.Center, ellipse.MajorAxis, ellipse.MinorAxis)
                    {
                        Color = ellipse.Color,
                        Layer = ellipse.Layer,
                        Linetype = ellipse.Linetype,
                        Lineweight = ellipse.Lineweight,
                        StartAngle = ellipse.StartAngle,
                        EndAngle = ellipse.EndAngle,
                        Rotation = ellipse.Rotation
                    };
                }
                else
                {
                    // 对于其他类型的实体，尝试使用内置的Clone方法
                    clonedEntity = entity.Clone() as EntityObject;
                }

                if (clonedEntity != null)
                {
                    // 复制通用属性
                    clonedEntity.Color = entity.Color;
                    clonedEntity.Layer = entity.Layer;
                    clonedEntity.Linetype = entity.Linetype;
                    clonedEntity.Lineweight = entity.Lineweight;
                    clonedEntity.Transparency = entity.Transparency;
                }

                return clonedEntity;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"克隆实体失败: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 应用变换
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="transformMatrix">变换矩阵</param>
        private void ApplyTransform(EntityObject entity, Matrix3 transformMatrix)
        {
            try
            {
                // 根据实体类型应用变换
                if (entity is Line line)
                {
                    // 变换起点和终点
                    line.StartPoint = TransformPoint(line.StartPoint, transformMatrix);
                    line.EndPoint = TransformPoint(line.EndPoint, transformMatrix);

                    System.Diagnostics.Debug.WriteLine($"Line变换: 起点({line.StartPoint.X:F2},{line.StartPoint.Y:F2}) -> 终点({line.EndPoint.X:F2},{line.EndPoint.Y:F2})");
                }
                else if (entity is Polyline2D polyline)
                {
                    // 变换所有顶点
                    foreach (var vertex in polyline.Vertexes)
                    {
                        var transformedPoint = TransformPoint(vertex.Position, transformMatrix);
                        vertex.Position = new Vector2(transformedPoint.X, transformedPoint.Y);
                    }

                    System.Diagnostics.Debug.WriteLine($"Polyline2D变换: 顶点数量={polyline.Vertexes.Count}");
                }
                else if (entity is Circle circle)
                {
                    // 变换圆心
                    var originalCenter = circle.Center;
                    circle.Center = TransformPoint(circle.Center, transformMatrix);

                    System.Diagnostics.Debug.WriteLine($"Circle变换: 圆心({originalCenter.X:F2},{originalCenter.Y:F2}) -> ({circle.Center.X:F2},{circle.Center.Y:F2})");
                }
                else if (entity is Arc arc)
                {
                    // 变换圆心
                    var originalCenter = arc.Center;
                    arc.Center = TransformPoint(arc.Center, transformMatrix);

                    System.Diagnostics.Debug.WriteLine($"Arc变换: 圆心({originalCenter.X:F2},{originalCenter.Y:F2}) -> ({arc.Center.X:F2},{arc.Center.Y:F2})");
                }
                else if (entity is Text text)
                {
                    // 变换文本位置
                    var originalPosition = text.Position;
                    text.Position = TransformPoint(text.Position, transformMatrix);

                    System.Diagnostics.Debug.WriteLine($"Text变换: 位置({originalPosition.X:F2},{originalPosition.Y:F2}) -> ({text.Position.X:F2},{text.Position.Y:F2})");
                }
                else if (entity is MText mtext)
                {
                    // 变换多行文本位置
                    var originalPosition = mtext.Position;
                    mtext.Position = TransformPoint(mtext.Position, transformMatrix);

                    System.Diagnostics.Debug.WriteLine($"MText变换: 位置({originalPosition.X:F2},{originalPosition.Y:F2}) -> ({mtext.Position.X:F2},{mtext.Position.Y:F2})");
                }
                else if (entity is Dimension dimension)
                {
                    // 对于标注实体，变换其定义点
                    // 这里需要根据具体的标注类型来处理
                    // 暂时跳过，避免复杂的标注变换逻辑
                    System.Diagnostics.Debug.WriteLine($"Dimension变换: 跳过复杂标注实体的变换");
                }
                else if (entity is Insert insert)
                {
                    // 对于Insert实体（块引用），变换其插入点
                    var originalPosition = insert.Position;
                    insert.Position = TransformPoint(insert.Position, transformMatrix);

                    System.Diagnostics.Debug.WriteLine($"Insert变换: 位置({originalPosition.X:F2},{originalPosition.Y:F2}) -> ({insert.Position.X:F2},{insert.Position.Y:F2})");
                }
                else if (entity is Point point)
                {
                    // 对于Point实体，变换其位置
                    var originalPosition = point.Position;
                    point.Position = TransformPoint(point.Position, transformMatrix);

                    System.Diagnostics.Debug.WriteLine($"Point变换: 位置({originalPosition.X:F2},{originalPosition.Y:F2}) -> ({point.Position.X:F2},{point.Position.Y:F2})");
                }
                else if (entity is MLine mline)
                {
                    // 对于MLine实体（多线），变换其顶点
                    var originalVertices = mline.Vertexes.ToList();
                    foreach (var vertex in mline.Vertexes)
                    {
                        var transformedPoint = TransformPoint(vertex.Position, transformMatrix);
                        vertex.Position = new Vector2(transformedPoint.X, transformedPoint.Y);
                    }

                    System.Diagnostics.Debug.WriteLine($"MLine变换: 顶点数量={mline.Vertexes.Count}");
                }
                else if (entity is Ellipse ellipse)
                {
                    // 对于Ellipse实体（椭圆），变换其中心点
                    var originalCenter = ellipse.Center;
                    ellipse.Center = TransformPoint(ellipse.Center, transformMatrix);

                    System.Diagnostics.Debug.WriteLine($"Ellipse变换: 圆心({originalCenter.X:F2},{originalCenter.Y:F2}) -> ({ellipse.Center.X:F2},{ellipse.Center.Y:F2})");
                }
                else
                {
                    // 对于其他类型的实体，尝试使用通用的变换方法
                    // 如果实体支持变换，可以调用相应的方法
                    System.Diagnostics.Debug.WriteLine($"未知实体类型变换: {entity.GetType().Name}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"应用变换失败: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"异常堆栈: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// 变换点坐标
        /// </summary>
        /// <param name="point">原始点</param>
        /// <param name="matrix">变换矩阵</param>
        /// <returns>变换后的点</returns>
        private Vector2 TransformPoint(Vector2 point, Matrix3 matrix)
        {
            // 应用变换矩阵：newPoint = point * matrix
            double x = point.X * matrix.M11 + point.Y * matrix.M21 + matrix.M31;
            double y = point.X * matrix.M12 + point.Y * matrix.M22 + matrix.M32;

            return new Vector2(x, y);
        }

        /// <summary>
        /// 变换点坐标（Vector3版本）
        /// </summary>
        /// <param name="point">原始点</param>
        /// <param name="matrix">变换矩阵</param>
        /// <returns>变换后的点</returns>
        private Vector3 TransformPoint(Vector3 point, Matrix3 matrix)
        {
            // 应用变换矩阵：newPoint = point * matrix
            double x = point.X * matrix.M11 + point.Y * matrix.M21 + matrix.M31;
            double y = point.X * matrix.M12 + point.Y * matrix.M22 + matrix.M32;
            double z = point.X * matrix.M13 + point.Y * matrix.M23 + matrix.M33;

            return new Vector3(x, y, z);
        }
    }
}
